﻿using System.Collections.Concurrent;
using MESTranslateToPLC.Service;

namespace MESTranslateToPLC.Manager;

public class ModbusDeviceManager
{
    private readonly ConcurrentDictionary<string, ModbusService> _devicePool;
    private readonly string _defaultIpAddress = "127.0.0.1";
    private readonly int _defaultPort = 502;

    public ModbusDeviceManager()
    {
        _devicePool = new ConcurrentDictionary<string, ModbusService>();
    }

    public async Task<bool> AddDeviceAsync(string ipAddress, int port)
    {
        try
        {
            var modbusService = GetDeviceService(ipAddress, port);
            if (modbusService != null)
            {
                return true;
            }

            string key = $"{ipAddress}:{port}";
            modbusService = new ModbusService(ipAddress, port);
            // await modbusService.Connect(ipAddress, port);
            if (_devicePool.TryAdd(key, modbusService))
                return true;
            return false;
        }
        catch (Exception e)
        {
            return false;
        }
    }

    public ModbusService? GetDeviceService(string ipAddress, int port)
    {
        string key = $"{ipAddress}:{port}";
        if (_devicePool.TryGetValue(key, out var service))
        {
            return service;
        }

        return null;
    }

    public ModbusService? GetDefaultDeviceService()
    {
        string key = $"{_defaultIpAddress}:{_defaultPort}";
        if (_devicePool.TryGetValue(key, out var service))
        {
            return service;
        }

        return null;
    }

    public async Task Init()
    {
        await AddDeviceAsync(_defaultIpAddress, _defaultPort);
    }
}